package com.xinke.module.system.service.dict;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.xinke.module.system.model.vo.dict.*;
import com.xinke.module.system.model.entity.dict.DictDataDO;
import com.xinke.component.common.pojo.PageResult;
import com.xinke.component.common.pojo.PageParam;
import com.xinke.component.common.util.object.BeanUtils;

import com.xinke.module.system.mapper.dict.DictDataMapper;

import static com.xinke.component.common.exception.util.ServiceExceptionUtil.exception;
import static com.xinke.module.system.enums.ErrorCodeConstants.*;

/**
 * 字典数据 Service 实现类
 *
 * @author yzx
 */
@Service
@Validated
public class DictDataServiceImpl implements DictDataService {
    /**
     * 排序 dictType > sort
     */
    private static final Comparator<DictDataDO> COMPARATOR_TYPE_AND_SORT = Comparator
            .comparing(DictDataDO::getDictItem)
            .thenComparingInt(DictDataDO::getDataSort);
    @Resource
    private DictDataMapper dictDataMapper;

    @Override
    public Long createDictData(DictDataSaveReqVO createReqVO) {
        // 插入
        DictDataDO dictData = BeanUtils.toBean(createReqVO, DictDataDO.class);
        dictDataMapper.insert(dictData);
        // 返回
        return dictData.getDataId();
    }

    @Override
    public void updateDictData(DictDataSaveReqVO updateReqVO) {
        // 校验存在
        validateDictDataExists(updateReqVO.getDataId());
        // 更新
        DictDataDO updateObj = BeanUtils.toBean(updateReqVO, DictDataDO.class);
        dictDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteDictData(Long ddId) {
        // 校验存在
        validateDictDataExists(ddId);
        // 删除
        dictDataMapper.deleteById(ddId);
    }

    private void validateDictDataExists(Long ddId) {
        if (dictDataMapper.selectById(ddId) == null) {
            throw exception(null);
        }
    }

    @Override
    public DictDataDO getDictData(Long ddId) {
        return dictDataMapper.selectById(ddId);
    }

    @Override
    public PageResult<DictDataDO> getDictDataPage(DictDataPageReqVO pageReqVO) {
        return dictDataMapper.selectPage(pageReqVO);
    }
    @Override
    public List<DictDataDO> getDictDataList(Integer status, String dictType) {
        List<DictDataDO> list = dictDataMapper.selectListByStatusAndDictType(status, dictType);
        list.sort(COMPARATOR_TYPE_AND_SORT);
        return list;
    }
}